#!/bin/bash

VERBOSE=0
OUTFILE=
IPS=

usage()
{
        echo "Usage: $0 [-v] [-h] -o OUTFILE HOST1 HOST2 ..."
}

sniffer()
{
        if [ -e $OUTFILE ]; then
                echo "$OUTFILE exists"
                return 17
        fi

        dir=$(mktemp -d)
        if [ $? -ne 0 ]; then
                echo "create temp directory failed"
                return $?
        fi

        for ip in $IPS; do
                echo "sniffer $ip ... "

                info=$(ssh root@$ip 'tmp=/$(mktemp license.XXXXXXXXXX) && /opt/fusionstack/lich/libexec/lich.license -m sniffer -o $tmp && echo $tmp')
                if [ $? -ne 0 ]; then
                        echo "error"
                        return $?
                fi

                scp root@$ip:$info $dir/$ip.info > /dev/null 2>&1 && ssh root@$ip 'rm -f $info'
                if [ $? -ne 0 ]; then
                        echo "error"
                        return $?
                fi
        done

        tar cf $OUTFILE $dir/* > /dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "tar error"
                return $?
        fi

	rm -rf $dir
}

while getopts vho: option; do
        case $option in
                v)
                        VERBOSE=1
                        break
                        ;;
                h)
                        usage
                        exit 0
                        ;;
                o)
                        OUTFILE="$OPTARG"
                        ;;
                ?)
                        usage
                        exit 1
                        ;;
        esac
done

shift $(($OPTIND - 1))
IPS="$*"

if [ -z "$OUTFILE" ] || [ -z "$IPS" ]; then
        usage
        exit 2
fi

sniffer
exit $?
